package com.fzx.fzwsupplysystem;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.Interface.onFacecompareAutnResult;
import com.common.Facecompare;
import com.fzx.fzwsupplysystem.activity.MainActivity;
import com.fzx.fzwsupplysystem.util.AppConstant;
import com.fzx.fzwsupplysystem.util.LogUtil;
import com.fzx.fzwsupplysystem.util.SharePreferenceUtil;
import com.fzx.fzwsupplysystem.util.ToastUtil;
import com.fzx.fzwsupplysystem.view.CustomDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

/**
 * 类名：SplashActivity.java
 * 描述：欢迎页，显示一张图片，点击欢迎页进入身份核验，左下角连续5次点击弹出输入框设置赛事ID
 * 作者：FangZhiXin
 * 日期：2019/11/1 10:54
 */
public class SplashActivity extends AppCompatActivity {

    private static final String TAG = "SplashActivity";
    private RelativeLayout relativeLayout;

    private static final int H_SHOW_PRO = 101;
    private static final int H_HIDE_PRO = 102;
    private static final int H_INIT = 103;

    private String tempMathId;//用于网络连接失败后重连的id
    private boolean isMatchInfoSuccess = false;//获取赛事信息
    private MyHandler myHandler;
    private SharePreferenceUtil sharePreferenceUtil;

    private static class MyHandler extends Handler {
        private WeakReference<SplashActivity> mActivity;

        private MyHandler(SplashActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SplashActivity activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case H_SHOW_PRO:
                        activity.showProgressDialog("正在初始化，请稍后。。。");
                        break;
                    case H_HIDE_PRO:
                        activity.hideProgressDialog();
                        activity.requestMatchName(AppConstant.matchId);
                        break;
                    case H_INIT:
                        activity.initFaceCompare();
                        break;

                }
            }
        }
    }

    private long[] mHints = new long[5];

    public void SetID(View view) {
        System.arraycopy(mHints, 1, mHints, 0, mHints.length - 1);
        mHints[mHints.length - 1] = SystemClock.uptimeMillis();
        if (SystemClock.uptimeMillis() - mHints[0] <= 2000) {//多次点击前后不超过1000
            mHints = null;
            mHints = new long[5];
//            ToastUtil.showToast(this, "多次点击");
            showEditDialog();
        }
    }

    private long[] mBackClick = new long[3];

    public void Back(View view) {
        System.arraycopy(mBackClick, 1, mBackClick, 0, mBackClick.length - 1);
        mBackClick[mBackClick.length - 1] = SystemClock.uptimeMillis();
        if (SystemClock.uptimeMillis() - mBackClick[0] <= 2000) {//多次点击前后不超过1000
            mBackClick = null;
            mBackClick = new long[5];
//            ToastUtil.showToast(this, "多次点击");
            finish();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        LogUtil.i(TAG, "SplashActivity-->onCreate 首页");
        relativeLayout = findViewById(R.id.rl_content);
        relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: ");
                if (MyApplication.isInitFace()) {
                    if ("".equals(AppConstant.matchId) || "000000".equals(AppConstant.matchId)) {
                        ToastUtil.showToast(SplashActivity.this, "请设置赛事ID");
                        return;
                    }
                    if (!isMatchInfoSuccess) {
                        ToastUtil.showToast(SplashActivity.this, "赛事信息获取失败");
                        return;
                    }
                    Intent intent = new Intent(SplashActivity.this, MainActivity.class);
                    startActivity(intent);
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                } else {
                    ToastUtil.showToast(SplashActivity.this, "初始化失败");
                }

            }
        });
        Button btn_setId = findViewById(R.id.btn_setId);
        btn_setId.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showEditDialog();
                return true;
            }
        });

        myHandler = new MyHandler(this);
        myHandler.sendEmptyMessage(H_SHOW_PRO);
        new Thread(new Runnable() {
            @Override
            public void run() {
                initFaceCompare();
            }
        }).start();

        //初始化赛事ID，如果没有设置，就默认AppConstant.matchId，并保存本地
        sharePreferenceUtil = SharePreferenceUtil.getInstance(getApplicationContext());
        String spMatchId = sharePreferenceUtil.getStringValue(AppConstant.SP_MATCH_ID, "000000");
        if (!"000000".equals(spMatchId)) {
            AppConstant.matchId = spMatchId;
            sharePreferenceUtil.putStringValue(AppConstant.SP_MATCH_ID, AppConstant.matchId).apply();
        }
    }

    /**
     * 初始化人脸识别
     */
    private void initFaceCompare() {
        MyApplication.setInitFace(false);
        Facecompare.getInstance().faceInit(this.getApplicationContext(), new onFacecompareAutnResult() {
            @Override
            public void onResult(final boolean result, final String msg) {
                LogUtil.i(TAG, "初始化人脸识别成功");
                MyApplication.setInitFace(true);
                myHandler.sendEmptyMessage(H_HIDE_PRO);
            }
        });

    }

    private void requestMatchName(final String id) {
        tempMathId = id;
        showProgressDialog("请稍后");
        isMatchInfoSuccess = false;
        OkGo.<String>get(AppConstant.URL_MATCH_INFO).tag(this)
                .params("matchId", id)//赛事id
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        hideProgressDialog();
                        if (response == null) {
                            showMessageDialog("提示", "数据异常，请重试\n null");
                            return;
                        }
                        String body = response.body();
                        LogUtil.i(TAG, "请求赛事信息 --> onSuccess: " + body);
                        try {
                            JSONObject jsonObject = new JSONObject(body);
                            String code = jsonObject.getString("code");
                            if ("000000".equals(code)) {
                                isMatchInfoSuccess = true;
                                sharePreferenceUtil.putStringValue(AppConstant.SP_MATCH_ID, id).apply();
                                AppConstant.matchId = id;
                                String matchChNm = jsonObject.getString("matchChNm");
                                String matchEnNm = jsonObject.getString("matchEnNm");
                                String matchId = jsonObject.getString("matchId");
                                MyApplication.setMatchChNm(matchChNm);
                                MyApplication.setMatchEnNm(matchEnNm);
                                MyApplication.setMatchID(matchId);
                            } else {
                                String reason = jsonObject.getString("reason");
                                showMessageDialog("提示", "请求异常，请重试\n" + reason);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            showMessageDialog("提示", "数据异常，请重试\n" + e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        hideProgressDialog();
                        showMessageDialog("提示", "网络异常，请重试");
                        LogUtil.e(TAG, "请求赛事信息失败 --> onError: ");
                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }


    private ProgressDialog progressDialog;

    private void showProgressDialog(String msg) {
        hideProgressDialog();
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private CustomDialog customDialog;

    private void showMessageDialog(String title, String msg) {
        hideMessageDialog();
        if (customDialog == null) {
            customDialog = new CustomDialog(this, 400, 200, R.style.DialogStyle);
        }
        customDialog.setBackgroundResource(R.color.colorWhite);
        customDialog.setTitle(title);
        customDialog.setMessage(msg);
        customDialog.setCanceledOnTouchOutside(false);
        customDialog.setButtonBackground(R.drawable.selector_dialog_btn);
        customDialog.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: ");
                requestMatchName(tempMathId);
            }
        });
        customDialog.setNegativeButton("退出", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customDialog.closeDialog();
                finish();
            }
        });
        customDialog.show();
    }

    private void hideMessageDialog() {
        if (customDialog != null && customDialog.isShowing()) {
            customDialog.closeDialog();
        }
    }

    private AlertDialog alertDialog;

    /**
     * 设置赛事ID输入框
     */
    private void showEditDialog() {
        String matchId = sharePreferenceUtil.getStringValue(AppConstant.SP_MATCH_ID, "000000");
        Log.i(TAG, "showEditDialog: matchId=" + matchId);
        hideEditDialog();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_dialog_edit_layout, null);
        builder.setView(view);
//        builder.setTitle("设置");
        final EditText et = view.findViewById(R.id.et_id);
        Button btn_submit = view.findViewById(R.id.btn_submit);
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String id = et.getText().toString().trim();
                if ("".equals(id)) {
                    ToastUtil.showToast(SplashActivity.this, "请输入赛事ID");
                    return;
                }
                requestMatchName(id);
                hideEditDialog();
            }
        });
        alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        if (window != null) {
            window.setLayout(400, 180);
        }
    }

    private void hideEditDialog() {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideProgressDialog();
        hideEditDialog();
        hideMessageDialog();
    }
}
